//
//  TryHoneJumpManage.m
//  THBaseApp
//
//  Created by TryHone on 16/12/26.
//  Copyright © 2016年 TryHone. All rights reserved.
//

#import "JFJumpManage.h"
#import <objc/runtime.h>
#import "JFUrlRouterManage.h"
#import "JFStringHelper.h"
#import "JFBaseWebViewController.h"



@implementation JFJumpConfiguration
+(JFJumpConfiguration*)defaultJFJumpConfiguration{
    JFJumpConfiguration * config = [[JFJumpConfiguration alloc] init];
    config.animation = YES;
    config.type = JUMP_TYPE_ALL;
    return config;
}
@end

@implementation JFJumpManage

+(JFJumpManage *)shareInstance
{
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [[self alloc]init];
    });
    return instance;
}
-(instancetype)init{
    self=[super init];
    if (self) {
    }
    return  self;
}

+(void)jump:(id __nonnull)jumpidenfication  param:(NSDictionary * __nullable)dict targetVc:(JFJumpManageVcBlock __nullable)targetVcblock config:(JFJumpConfiguration*)config  callBack:(baseCallBack __nullable)back completion:(void (^ )(void))completion{
    [[JFJumpManage shareInstance] jump:jumpidenfication param:dict targetVc:targetVcblock config:config callBack:back completion:completion];
}

-(void)jump:(id)jumpidenfication  param:(NSDictionary* __nullable)dict targetVc:(JFJumpManageVcBlock __nullable)targetVcblock config:(JFJumpConfiguration*)config  callBack:(baseCallBack __nullable)back completion:(void (^ )(void))completion{
    
    if(!jumpidenfication){
        return;
    }
    if (!back) {
        back=^(id data){
        };
    }
    if(!config){
        config = [JFJumpConfiguration defaultJFJumpConfiguration];
    }
     UINavigationController *nav=nil;
     nav=[self getCurrentNavVC];//当前导航栏控制器
     UIViewController* idvc = nil;
     idvc = [self targetVc:jumpidenfication dict:dict];
     if (idvc) {

        NSMutableDictionary * propertys =[[NSMutableDictionary alloc] initWithDictionary:dict] ;
        //给目标控制器参数设置值
        [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            // 检测这个对象是否存在该属性
            if ([self checkIsExistPropertyWithInstance:idvc verifyPropertyName:key]) {
                [idvc setValue:obj forKey:key];
            }
        }];
        //针对base类
         if([idvc isKindOfClass:[JFBaseViewController class]]){
             [idvc setValue:propertys forKey:@"userInfo"];
             [idvc setValue:back forKey:@"callBack"];
         }
        if(targetVcblock){
            targetVcblock(idvc);
        }
        
        
        switch (config.type) {
            case JUMP_TYPE_PUSH:
            {
                [self pushJumpType:nav toVc:idvc animated:config.animation];
            }break;
            case JUMP_TYPE_MODLE:
            {
                [self presentJumpTypeToVc:idvc animated:config.animation completion:completion];
            }break;
            default:{
                [self allJumpType:nav toVc:idvc animated:config.animation completion:completion];
            }break;
        }
    }
    
    
}
-(UIViewController*)targetVc:(id)jumpidenfication dict:(NSDictionary*)dict{
    
    UIViewController* idvc = nil;
    if([jumpidenfication isKindOfClass:[NSString class]]){
        NSString * jumpidenficationStr = (NSString *)jumpidenfication;
        NSString * tempJumpidenficationStr = [[jumpidenficationStr copy] lowercaseString];
        if([JFStringHelper stringContain:tempJumpidenficationStr subStr:@":"]){//非标识字符串
            NSArray * arr = [tempJumpidenficationStr componentsSeparatedByString:@":"];
            NSArray * arrTrue = [jumpidenficationStr componentsSeparatedByString:@":"];
            NSString * jumpidenficationStr = (NSString *)jumpidenfication;
            NSString * prefix = [arr firstObject];
            if([@"app" isEqualToString:prefix]){
                NSString * vcClassStr = [arrTrue lastObject];
                Class class = NSClassFromString(vcClassStr);
                //如果存在实例插件
                if (class)
                {
                    id instance = [[class alloc] init];
                    if([instance isKindOfClass:[UIViewController class]]){
                        idvc = (UIViewController*)instance;
                    }
                }
            }else if ([@"xib" isEqualToString:prefix]){
                NSString * vcClassStr = [arrTrue lastObject];
                NSString * svcClassStr = vcClassStr;
                if(vcClassStr){
                    NSArray * vcData = [vcClassStr componentsSeparatedByString:@"/"];
                    if(vcData.count>1){//xib:xx/AVC 或者 xib:xxx.buddle/AVC
                        NSString * buddleName = vcData[0];
                        svcClassStr = vcData[1];
                        if(buddleName){
                            NSArray * buddleData = [vcClassStr componentsSeparatedByString:@"."];
                            if(buddleData.count>1){//传了后缀的
                                NSString *resourceBundlePath = [[NSBundle mainBundle] pathForResource:buddleData[0] ofType:@"bundle"];
                                NSBundle *buddle = [NSBundle bundleWithPath:resourceBundlePath];
                                idvc = [self getXibVcFromBuddle:buddle className:svcClassStr nibName:svcClassStr];
                            }else{//没有后缀的 直接默认是buddle
                                NSString *resourceBundlePath = [[NSBundle mainBundle] pathForResource:buddleName ofType:@"bundle"];
                                NSBundle *buddle = [NSBundle bundleWithPath:resourceBundlePath];
                                idvc = [self getXibVcFromBuddle:buddle className:svcClassStr nibName:svcClassStr];
                            }
                            
                        }
                    }else{//xib:AVC
                        idvc = [self getXibVcFromBuddle:nil className:vcClassStr nibName:vcClassStr];
                    }
                }
                
                
            }else if ([@"storyboard" isEqualToString:prefix]){
                if(arrTrue.count == 3){
                    NSString * idStr = arrTrue[2];
                    NSString * storyboardName = arrTrue[1];
                    if([JFStringHelper isNotEmpty:idStr]){
                        if([JFStringHelper isEmpty:storyboardName]){
                            storyboardName = @"Main";
                        }
                        NSArray * storyboardNameData = [storyboardName componentsSeparatedByString:@"/"];
                        if(storyboardNameData.count>1){
                            NSString *resourceBundlePath = [[NSBundle mainBundle] pathForResource:storyboardNameData[0] ofType:@"bundle"];
                            NSBundle *buddle = [NSBundle bundleWithPath:resourceBundlePath];
                            idvc = [self getstoryboardVCFromBuddle:buddle storyboardName:storyboardNameData[1] idStr:idStr];
                        }else{

                            idvc = [self getstoryboardVCFromBuddle:nil storyboardName:storyboardName idStr:idStr];
                        }
                     }
               }
            }else if([@"http" isEqualToString:prefix]||[@"https" isEqualToString:prefix]){
                JFBaseWebViewController * webVc = [[JFBaseWebViewController alloc] init];
                webVc.urlStr = jumpidenficationStr;
                webVc.hidesBottomBarWhenPushed = YES;
                idvc = webVc;
            }
        }else{
            NSString * strTemp =[JFUrlRouterManage vcWithIdenfication:jumpidenfication];
            if(strTemp){
               idvc = [self targetVc:strTemp dict:dict];
            }

        }
   
    }else if([jumpidenfication isKindOfClass:[UIViewController class]]){
        idvc  = (UIViewController*)jumpidenfication;
    }
    
   return idvc;
}
-(UIViewController*)getXibVcFromBuddle:(NSBundle*)buddle className:(NSString*)className nibName:(NSString*)nibName{
     UIViewController* idvc = nil;
    Class class = NSClassFromString(className);
    //如果存在实例插件
    if (class)
    {
        id instance = [class alloc];
        if([instance respondsToSelector:@selector(initWithNibName:bundle:)]){
            instance = [instance initWithNibName:nibName bundle:buddle];
            if([instance isKindOfClass:[UIViewController class]]){
                idvc = (UIViewController*)instance;
            }
        }
    }
    return idvc;
}
-(UIViewController*)getstoryboardVCFromBuddle:(NSBundle*)buddle storyboardName:(NSString*)storyboardName idStr:(NSString*)idStr{
       UIViewController* idvc = nil;
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:storyboardName bundle:buddle];
    UIViewController *controller=[storyboard instantiateViewControllerWithIdentifier:idStr];
    if(controller){
        idvc = controller;
    }
    return idvc;
}

/**
 *  @author Alan, 16-12-26 19:12:30
 *
 *  @brief 回到上一个界面
 */
+(void)backPreviousPage:(void (^)(void))completion{
    UIViewController* vc=[[JFJumpManage shareInstance] getCurrentVC];
    UINavigationController * nav=[[JFJumpManage shareInstance] getCurrentNavVC];
    if (nav) {
       
        if(completion){
            [vc dismissViewControllerAnimated:YES completion:completion];
        }else{
            if(nav.viewControllers.count == 1){
                [vc dismissViewControllerAnimated:YES completion:completion];
            }else{
                [nav popViewControllerAnimated:YES];
            }
        }
    }else{
        [vc dismissViewControllerAnimated:YES completion:completion];
    }

}
-(void)pushJumpType:(UINavigationController*)nav  toVc:(UIViewController*)idvc animated:(BOOL)animated
{
    if (nav) {
        [nav pushViewController:idvc animated:animated];
    }
}

-(void)presentJumpTypeToVc:(UIViewController*)idvc  animated:(BOOL)animated completion:(void (^ _Nullable)(void))completion
{
    UIViewController * vc = [self getCurrentVC] ;
    
    if(vc){
        if (![idvc isKindOfClass:[UINavigationController class]]) {
            UINavigationController* navc=[[UINavigationController alloc] initWithRootViewController:idvc];
            [navc setNavigationBarHidden:YES animated:NO];
            [vc presentViewController:navc animated:animated completion:completion];
        }else{
            [vc presentViewController:idvc animated:animated completion:completion];
        }
    }else{
        
        UIWindow * windows =  [UIApplication sharedApplication].keyWindow;
        if(!windows){
            windows = [[UIApplication sharedApplication].windows firstObject];
        }
        
        if(windows){
            windows.rootViewController = idvc;
            [windows makeKeyAndVisible];
        }
       
        
    }
    

}

-(void)allJumpType:(UINavigationController*)nav toVc:(UIViewController*)idvc animated:(BOOL)animated completion:(void (^ _Nullable)(void))completion
{
    if (nav) {
        [self pushJumpType:nav toVc:idvc animated:animated];
    }else{
        [self presentJumpTypeToVc:idvc animated:animated completion:completion];
    }

}
#pragma mark--内部使用的方法
/**
 *  @author Alan, 16-12-26 15:12:49
 *
 *  @brief 获取当前显示的控制器
 *
 *  @return 控制器实例
 */
//- (UIViewController *)getCurrentVC
//{
//    UIViewController * result = nil;
//    UIWindow * window = [self getCurrentWindow];
//    UIView *frontView = [[window subviews] objectAtIndex:0];
//    id nextResponder = [frontView nextResponder];
//
//
//    if ([nextResponder isKindOfClass:[UITabBarController class]]) {
//        UITabBarController* tab=(UITabBarController*)nextResponder;
//        result=tab.selectedViewController;
//    }else{
//        if ([nextResponder isKindOfClass:[UIViewController class]])
//        {
//            result = nextResponder;
//        }
//        else
//        {
//
//            result = window.rootViewController;
//        }
//    }
//    return result;
//}


-(UIViewController *)getCurrentVC{
//    UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
//    UIViewController *parent = rootVC;
//    while ((parent = rootVC.presentedViewController) != nil ) {
//        rootVC = parent;
//    }
//    while ([rootVC isKindOfClass:[UINavigationController class]]) {
//        rootVC = [(UINavigationController *)rootVC topViewController];
//    }
//    return rootVC;
    
//    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
//    UIViewController *vc = keyWindow.rootViewController;
//    while (vc.presentedViewController) {
//        vc = vc.presentedViewController;
//
//        if ([vc isKindOfClass:[UINavigationController class]]) {
//            vc = [(UINavigationController *)vc visibleViewController];
//        } else if ([vc isKindOfClass:[UITabBarController class]]) {
//            vc = [(UITabBarController *)vc selectedViewController];
//        }
//    }
//    return vc;
    
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
    
}



- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    
    return currentVC;
}




/**
 *  @author Alan, 16-12-26 15:12:48
 *
 *  @brief 获取当前的window
 *
 */
-(UIWindow*)getCurrentWindow{
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    return window;
}
/**
 *  @author Alan, 16-12-26 15:12:03
 *
 *  @brief 获取当前的导航栏控制器
 *
 */
-(UINavigationController*)getCurrentNavVC{
    UINavigationController* nav=nil;
    UIViewController* cvc=[self getCurrentVC];
    if (cvc) {
        if ([cvc isKindOfClass:[UINavigationController class]]) {
            nav=(UINavigationController*)cvc;
        }if([cvc isKindOfClass:[UITabBarController class]]){
            UITabBarController * tab = (UITabBarController*)cvc;
            UIViewController * vc  = tab.selectedViewController;
            if ([vc isKindOfClass:[UINavigationController class]]) {
                 nav=(UINavigationController*)vc;
            }else{
                nav = nav.navigationController;
            }
        }else{
            nav = [self getCurrentVC].navigationController;
            if(!nav){//最顶层的控制器没有获取到导航栏
                if ([self isPresentCurrentVC]){//获取
                    nav = [self getCurrentVC].presentingViewController.navigationController;
                }
            }
        }
    }
    return  nav;
}
/**
 *  @author Alan, 16-12-26 16:12:11
 *
 *  @brief 判断当前控制器是不是模态方式弹出的
 *
 */
-(BOOL)isPresentCurrentVC{
    UIViewController * vc=[self getCurrentVC];
    if (vc.presentingViewController) {//有前置模态控制器说明当前控制器是模态方式弹出的
        return YES;
    }else{
        return NO;
    }
}
/**
 *  @author Alan, 16-12-26 17:12:14
 *
 *  @brief 检查一个类里是否包含该属性
 *
 *  @param instance           类实例变量
 *  @param verifyPropertyName 属性名字
 *
 */
- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance
                                                           class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}



+ (void)jumpUserHomeWithUserId:(NSInteger)userId {
    JFMsgCenterVo * msg = [[JFMsgCenterVo alloc] init];
    msg.from = @"BASE";
    msg.to = @"DIS";
    msg.requestNum = @"900001";
    msg.params = @{@"userId":@(userId).stringValue};
    [JFMsgCenteManager requestWithMsgCenterVo:msg callback:nil];
}


@end
